package com.fzn.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @author fzn
 * @date 2022/3/18
 * @apiNote 自定义Realm实现 加入MD5和salt和随机hash
 */
public class CustomerMD5Realm extends AuthorizingRealm {
    /**
     * 授权
     *
     * @param principals 身份集合
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("====================");
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("身份信息："+primaryPrincipal);
        // 根据身份信息 用户名 获取当前用户的角色信息 以及权限信息 xiaochen   admin    users
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 将数据库查询角色信息赋值给对象
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addRole("users");

        // 将数据库中查询权限信息赋值给权限对象  user:*:01 01 用户的所有权限
        simpleAuthorizationInfo.addStringPermission("user:*:01");
        simpleAuthorizationInfo.addStringPermission("product:create");

        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 在token中获取用户名
        String principal = (String) token.getPrincipal();
        System.out.println(principal);
        // 根据身份信息使用jdbc mybatis查询相关数据库
        if ("xiaochen".equals(principal)) {
            // 参数1 正确用户名    参数2返回数据库正确的密码   参数3 提供当前realm的名字 this.getName()
            //SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal,"202cb962ac59075b964b07152d234b70",this.getName());
            // 加入随机盐  ByteSource.Util.bytes("X0*7ps"),
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                    principal,
                    "e4f9bf3e0c58f045e62c23c533fcf633",
                    ByteSource.Util.bytes("X0*7ps"),
                    this.getName());
            // 加hash e4f9bf3e0c58f045e62c23c533fcf633
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
